"""
AI Agent Pro - 演示脚本
展示如何创建和使用智能体
"""

import asyncio
import os
import sys
from pathlib import Path
from typing import Dict, Any

# 添加backend目录到Python路径
backend_path = Path(__file__).parent / "backend"
sys.path.insert(0, str(backend_path))

# 设置环境变量 (演示用途)
os.environ.setdefault("SECRET_KEY", "demo_secret_key_change_in_production")
os.environ.setdefault("DATABASE_URL", "sqlite:///demo.db")
os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")

from app.agents.core import Agent, AgentConfig, AgentFactory
from app.agents.models.base import AgentModel, ModelConfig, ModelResponse


class MockModel(AgentModel):
    """模拟AI模型 (用于演示)"""
    
    def __init__(self, model_name: str = "mock-gpt-4"):
        config = ModelConfig(
            model_name=model_name,
            api_key="mock_api_key",
            temperature=0.7,
            max_tokens=2000
        )
        super().__init__(config)
    
    async def generate(self, prompt: str, system_prompt: str = None, **kwargs) -> str:
        """模拟生成响应"""
        # 简单的模拟逻辑
        if "你好" in prompt or "hello" in prompt.lower():
            return "你好！我是AI智能体助手，很高兴为您服务！我可以帮您处理各种任务。"
        elif "编程" in prompt or "代码" in prompt:
            return """我可以帮您编写和调试代码！以下是一个简单的Python函数示例：

```python
def greet(name):
    return f"Hello, {name}!"

# 使用示例
print(greet("World"))
```

需要什么具体的编程帮助吗？"""
        elif "计算" in prompt or "math" in prompt.lower():
            return "我可以帮您进行数学计算和分析。请告诉我具体需要计算什么？"
        else:
            return f"我理解您的问题：{prompt[:50]}{'...' if len(prompt) > 50 else ''}。让我为您详细分析和回答。"
    
    async def generate_stream(self, prompt: str, system_prompt: str = None, **kwargs):
        """模拟流式生成"""
        response = await self.generate(prompt, system_prompt, **kwargs)
        words = response.split()
        for word in words:
            yield word + " "
            await asyncio.sleep(0.1)
    
    async def generate_with_tools(self, prompt: str, tools: list, system_prompt: str = None, **kwargs):
        content = await self.generate(prompt, system_prompt, **kwargs)
        return ModelResponse(
            content=content,
            usage={"input_tokens": 100, "output_tokens": 50},
            model=self.model_name,
            finish_reason="stop"
        )
    
    async def create_embedding(self, text: str, **kwargs):
        """模拟嵌入向量"""
        import random
        return [random.random() for _ in range(1536)]


async def demo_basic_agent():
    """演示基础智能体功能"""
    print("🤖 AI Agent Pro 演示")
    print("=" * 50)
    
    # 创建智能体配置
    config = AgentConfig(
        name="演示助手",
        description="一个用于演示的AI助手",
        model="mock-gpt-4",
        temperature=0.7,
        system_prompt="你是一个友好、专业的AI助手，能够帮助用户解决各种问题。",
        thinking_enabled=True,
        memory_enabled=False  # 简化演示，不启用记忆
    )
    
    # 创建模拟模型
    mock_model = MockModel()
    
    # 创建智能体实例
    agent = Agent(config)
    agent.model = mock_model  # 替换为模拟模型
    
    print(f"✅ 智能体创建成功: {agent.config.name}")
    print(f"🆔 智能体ID: {agent.id}")
    print(f"🧠 使用模型: {agent.config.model}")
    print()
    
    # 测试对话
    test_messages = [
        "你好！",
        "你能帮我写一个Python函数吗？",
        "计算 15 * 23 = ?",
        "什么是机器学习？"
    ]
    
    for i, message in enumerate(test_messages, 1):
        print(f"👤 用户 {i}: {message}")
        
        try:
            # 获取回复
            response = await agent.chat(message, user_id="demo_user")
            print(f"🤖 助手: {response}")
            
        except Exception as e:
            print(f"❌ 错误: {str(e)}")
        
        print("-" * 40)
    
    # 显示智能体状态
    status = agent.get_status()
    print("\n📊 智能体状态:")
    for key, value in status.items():
        print(f"  {key}: {value}")


async def demo_stream_chat():
    """演示流式对话"""
    print("\n🌊 流式对话演示")
    print("=" * 50)
    
    config = AgentConfig(
        name="流式助手",
        model="mock-gpt-4",
        thinking_enabled=False  # 简化演示
    )
    
    agent = Agent(config)
    agent.model = MockModel()
    
    message = "请详细介绍一下人工智能的发展历史"
    print(f"👤 用户: {message}")
    print("🤖 助手 (流式): ", end="", flush=True)
    
    try:
        async for chunk in agent.chat(message, stream=True):
            print(chunk, end="", flush=True)
        print()  # 换行
        
    except Exception as e:
        print(f"\n❌ 流式对话错误: {str(e)}")


async def demo_agent_factory():
    """演示智能体工厂"""
    print("\n🏭 智能体工厂演示")
    print("=" * 50)
    
    # 使用模板创建智能体
    try:
        coding_agent = AgentFactory.create_from_template(
            template_name="coding_assistant",
            name="我的编程助手",
            temperature=0.1  # 编程任务需要更准确的输出
        )
        
        # 替换为模拟模型
        coding_agent.model = MockModel("mock-gpt-4-code")
        
        print(f"✅ 编程助手创建成功: {coding_agent.config.name}")
        print(f"🔧 可用工具: {coding_agent.config.tools}")
        
        # 测试编程相关对话
        response = await coding_agent.chat("帮我写一个冒泡排序算法")
        print(f"👤 用户: 帮我写一个冒泡排序算法")
        print(f"🤖 编程助手: {response}")
        
    except Exception as e:
        print(f"❌ 创建编程助手失败: {str(e)}")


def print_feature_overview():
    """打印功能概览"""
    print("\n🚀 AI Agent Pro 核心功能")
    print("=" * 50)
    
    features = {
        "🧠 智能体引擎": [
            "多模型支持 (OpenAI GPT, Anthropic Claude)",
            "可配置的推理参数",
            "思考过程展示",
            "状态管理和监控"
        ],
        "🛠️ 工具系统": [
            "可插拔工具架构",
            "内置常用工具",
            "自定义工具支持",
            "安全执行环境"
        ],
        "🧩 记忆管理": [
            "短期对话记忆",
            "长期知识存储",
            "语义搜索检索",
            "自动记忆整理"
        ],
        "🌐 API接口": [
            "RESTful API设计",
            "WebSocket实时通信",
            "流式响应支持",
            "完整的错误处理"
        ],
        "🔒 安全特性": [
            "JWT身份认证",
            "API访问控制",
            "输入安全验证",
            "审计日志记录"
        ],
        "📊 监控分析": [
            "性能指标收集",
            "使用统计分析",
            "错误追踪报告",
            "成本估算工具"
        ]
    }
    
    for category, items in features.items():
        print(f"\n{category}:")
        for item in items:
            print(f"  ✓ {item}")


async def main():
    """主演示函数"""
    print_feature_overview()
    
    try:
        # 基础智能体演示
        await demo_basic_agent()
        
        # 流式对话演示
        await demo_stream_chat()
        
        # 智能体工厂演示
        await demo_agent_factory()
        
        print("\n🎉 演示完成！")
        print("\n📝 后续步骤:")
        print("1. 配置真实的AI模型API密钥")
        print("2. 设置数据库和Redis")
        print("3. 实现自定义工具")
        print("4. 部署到生产环境")
        print("\n📚 查看完整文档: README.md")
        
    except Exception as e:
        print(f"\n❌ 演示过程中发生错误: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    # 运行演示
    asyncio.run(main())